package com.ilia.leek.job.jobhandler;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.dtflys.forest.http.ForestResponse;
import com.ilia.leek.entity.Fund;
import com.ilia.leek.entity.FundCompany;
import com.ilia.leek.fund.FundConstant;
import com.ilia.leek.fund.RequestTool;
import com.ilia.leek.fund.eastmoney.EastmoneyHttpClient;
import com.ilia.leek.fund.xiong.DoctorXiongHttpClient;
import com.ilia.leek.fund.xiong.DoctorXiongResponse;
import com.ilia.leek.fund.xiong.DoctorXiongUtil;
import com.ilia.leek.service.FundCompanyService;
import com.ilia.leek.service.FundService;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * XxlJob开发示例（Bean模式）
 * <p>
 * 开发步骤：
 * 1、任务开发：在Spring Bean实例中，开发Job方法；
 * 2、注解配置：为Job方法添加注解 "@XxlJob(value="自定义jobhandler名称", init = "JobHandler初始化方法", destroy = "JobHandler销毁方法")"，注解value值对应的是调度中心新建任务的JobHandler属性的值。
 * 3、执行日志：需要通过 "XxlJobHelper.log" 打印执行日志；
 * 4、任务结果：默认任务结果为 "成功" 状态，不需要主动设置；如有诉求，比如设置任务结果为失败，可以通过 "XxlJobHelper.handleFail/handleSuccess" 自主设置任务结果；
 *
 * @author xuxueli 2019-12-11 21:52:51
 */
@Component
@Slf4j
public class SampleXxlJob {
    private static final Logger logger = LoggerFactory.getLogger(SampleXxlJob.class);

    @Resource
    private DoctorXiongHttpClient doctorXiongHttpClient;

    @Resource
    private EastmoneyHttpClient eastmoneyHttpClient;

    @Resource
    private FundService fundService;
    @Resource
    private FundCompanyService fundCompanyService;

    /**
     * 1、获取全部基金
     */
    @XxlJob("allFund")
    public void allFund() throws Exception {
        XxlJobHelper.log("XXL-JOB, Hello World.");
        ForestResponse<DoctorXiongResponse> response = doctorXiongHttpClient.getAllFund(FundConstant.DOCTORXIONG_ALL_FUND);
        if (response.isSuccess()) {
            DoctorXiongResponse xiongResponse = response.getResult();
            if (xiongResponse.getCode().equals(DoctorXiongUtil.DOCTORXIONG_SUCCESS)) {
                List<Fund> list = new ArrayList<>();
                JSONArray jsonArray = JSONUtil.parseArray(xiongResponse.getData());
                jsonArray.stream().iterator().forEachRemaining(ele -> {
                    Fund fund = DoctorXiongUtil.resolveListFund((JSONArray) ele);
                    list.add(fund);
                });
//                XxlJobHelper.log(String.valueOf(list));
                XxlJobHelper.log("获取列表完毕,size:{}", list.size());
                List<Fund> funds = fundService.list();
                List<Fund> n = list.stream().filter(item -> !funds.contains(item)).collect(Collectors.toList());
                fundService.saveBatch(n);
                XxlJobHelper.log(String.valueOf(n));
                XxlJobHelper.log("更新操作完毕,更新size:{}", n.size());
            }
        }
        // default success
    }

    /**
     * 1、获取全部公司
     */
    @XxlJob("allFundCompany")
    public void allFundCompany() throws Exception {
        XxlJobHelper.log("XXL-JOB, Hello World.");

        ForestResponse<String> response = eastmoneyHttpClient.fundAllCompany(FundConstant.EASTMONEY_COMPANY, System.currentTimeMillis(), RequestTool.HEADER);
        if (response.isSuccess()) {
//                XxlJobHelper.log(String.valueOf(list));
            XxlJobHelper.log("获取列表完毕,content:{}", response.getContent());
            String data = response.getContent().substring(9);
            XxlJobHelper.log(data);
            JSONObject jsonObject = JSONUtil.parseObj(data);
            JSONArray array = jsonObject.getJSONArray("datas");
            List<FundCompany> list = new ArrayList<>();
            array.stream().iterator().forEachRemaining(ele -> {
                try {
                    FundCompany fundCompany = new FundCompany();
                    fundCompany.setCompanyCode(((JSONArray) ele).getStr(0));
                    fundCompany.setCompanyName(((JSONArray) ele).getStr(1));
                    fundCompany.setCompanyTime(LocalDateTime.parse(((JSONArray) ele).getStr(2), DATE_FORMATTER));
                    fundCompany.setCompanyPinyin(((JSONArray) ele).getStr(5));
                    fundCompany.setCompanyScope(((JSONArray) ele).getStr(7));
                    fundCompany.setCompanyRank(((JSONArray) ele).getStr(8));
                    fundCompany.setCompanyShort(((JSONArray) ele).getStr(9));
                    list.add(fundCompany);
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error(e.getMessage());
                }
            });
            List<FundCompany> companies = fundCompanyService.list();
            logger.info(String.valueOf(companies.size()));
            List<FundCompany> n = list.stream().filter(item -> !companies.contains(item)).collect(Collectors.toList());
            fundCompanyService.saveBatch(n);
            XxlJobHelper.log("更新操作完毕,更新size:{}", n.size());
        }
    }
    // default success

    DateTimeFormatter DATE_FORMATTER1 = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    DateTimeFormatter DATE_FORMATTER = new DateTimeFormatterBuilder().append(DATE_FORMATTER1)
            .parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
            .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
            .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
            .toFormatter();

    /**
     * 5、生命周期任务示例：任务初始化与销毁时，支持自定义相关逻辑；
     */
    @XxlJob(value = "demoJobHandler2", init = "init", destroy = "destroy")
    public void demoJobHandler2() throws Exception {
        XxlJobHelper.log("XXL-JOB, Hello World.");
    }

    public void init() {
        logger.info("init");
    }

    public void destroy() {
        logger.info("destroy");
    }


}
